<template>
  <view class="make_present">
    <view class="make_title">
      <text>可提现金额（元）</text>
      <text class="price">{{ totalAmount }}</text>
      <view class="but">
        <i-buttons
          @click="toDetail"
          radius="48rpx"
          padding="12rpx 36rpx"
          bgColor="transparent"
          color="#fff"
          >提现记录</i-buttons
        >
      </view>
    </view>
    <i-card top="20rpx">
      <i-formItem border="none" align="top" title="提现类型" :lBlod="true">
        <view
          @click="showDrawer = true"
          class="exchangeType"
          :style="{ color: formData.exchangeTypeStr ? '#222' : '#999' }"
          >{{ formData.exchangeTypeStr || "请选择提现类型" }}
          <uni-icons type="down" size="24" color="#999"></uni-icons>
        </view>
      </i-formItem>
      <i-formItem border="none" align="top" title="提现金额" :lBlod="true">
        <view style="display: flex; align-items: center">
          <text style="margin-right: 8rpx">￥</text>
          <input
            v-model="formData.giveAccountAmount"
            type="number"
            placeholder="请输入提现金额"
          />
        </view>
      </i-formItem>
      <i-formItem v-if="userCardList.length > 0" border="none" align="top" title="提现至" :lBlod="true">
        <!-- @click="showBank = true" -->
        <view
          class="exchangeType"
          :style="{ color: formData.selectBank ? '#222' : '#999' }"
        >
          <text v-if="formData.selectBank"
            >{{ formData.selectBank?.bankName }} -
            {{ formData.selectBank?.cardTypeStr }} -
            {{ bankEncryption(formData.selectBank?.bankcardNum) }}</text
          >
          <text v-else>请添加提现方式</text>
          <!-- <uni-icons type="down" size="24" color="#999"></uni-icons> -->
        </view>
      </i-formItem>
      <view class="bottoms">
        <i-buttons
          color="#fff"
          bgColor="linear-gradient( 90deg, #FFB413 0%, #FF9A00 100%)"
          radius="48rpx"
          padding="18rpx 0"
          size="32rpx"
          @click="confrim"
        >
          确认提现</i-buttons
        >
        <view style="height: 32rpx" v-if="userCardList.length === 0"></view>
        <i-buttons
          v-if="userCardList.length === 0"
          color="#FF9400"
          border="1px solid #FF9400"
          bgColor="#fff"
          radius="48rpx"
          padding="18rpx 0"
          size="32rpx"
          @click="handleAddBank"
        >
          添加提现方式</i-buttons
        >
      </view>
    </i-card>
  </view>
  <i-drawer
    v-model="showDrawer"
    @confirm="drawerConfirm"
    :list="bussinessPriceType"
    :confirm_title="false"
    :activeIndex="activeIndex"
  >
    <view></view>
  </i-drawer>
  <i-checkPay-modal
    :chcekPay="checkPay"
    @close="checkPay = false"
    @checkConfirm="checkConfirm"
  ></i-checkPay-modal>

  <i-popup v-model="showBank" title="选择提现方式">
    <view
      class="bank_list"
      v-for="(item, index) in userCardList"
      @click="selectBank(item, index)"
    >
      <view class="bank_item_left">
        <view class="bank_item_select">
          <image
            v-if="formData.userCardId === item.id"
            src="../../static/images/bank_select_icon.png"
          ></image>
          <view v-else style="margin-top: -6rpx">
            <uni-icons type="circle" size="24" color="#999"></uni-icons>
          </view>
        </view>
        <text class="bank_name">{{ item.bankName }}</text>
        <text style="color: #ff9400">{{ item.cardTypeStr }}</text>
        <text class="bank_cardNum">{{ item.bankcardNum }}</text>
      </view>
      <!-- 移除编辑和删除功能 -->
    </view>
    <view class="bottoms">
      <i-buttons
        @click="confrimSelect"
        color="#fff"
        bgColor="linear-gradient( 90deg, #FFB413 0%, #FF9A00 100%)"
        radius="48rpx"
        padding="18rpx 0"
        size="32rpx"
        >确认</i-buttons
      >
    </view>
  </i-popup>

  <i-popup
    v-model="showAddBank"
    :title="editBankData?.id ? '修改银行卡' : '添加银行卡'"
  >
    <AddBank :editBankData="editBankData" @addBank="addBank"></AddBank>
  </i-popup>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  addUserCard,
  addCashOrder,
} from "../../api/index";
import { getUserCardDetailNew } from "../../api/user";
import { phoneReg } from "../../utils/regs";
import { bankEncryption } from "../../utils/common";
import {
  showTost,
  withdrawalType as bussinessPriceType,
  exchangeTypeEnum,
} from "../../utils/common";
import useStore from "../../stores/index";
import AddBank from "./components/addBank.vue";

const store = useStore();
const totalAmount = ref("");
const activeIndex = ref(0);
const showDrawer = ref(false);
const checkPay = ref(false);
const showBank = ref(false);
const showAddBank = ref(false);
const userCardList = ref<any>([]);
const editBankData = ref<any>(null);

const userInfo = computed(() => {
  // totalAmount.valu e = store.userInfo[exchangeTypeEnum[formData.exchangeType]];
  return store.userInfo;
});

const formData = reactive<any>({
  giveAccountAmount: "",
  mobile: "",
  userCardId: "",
  selectBank: null,
});

const getUserCardList = async () => {
  try {
    const { data } = await getUserCardDetailNew();
    // 适配新的数据结构，将单个对象转换为数组
    // 使用身份证号判断是否有有效的提现方式
    if (data && data.identityNumber) {
      userCardList.value = [data];
      // 自动选择唯一的提现方式
      formData.userCardId = data.id;
      formData.selectBank = data;
    } else {
      userCardList.value = [];
      formData.userCardId = "";
      formData.selectBank = null;
    }
  } catch (e) {
    console.log(e);
  }
};
const handleAddBank = () => {
  showAddBank.value = true;
  editBankData.value = null;
};
const confrimSelect = async () => {
  if (!formData.userCardId) {
    showTost("请选择添加方式");
    return;
  }
  showBank.value = false;
  formData.selectBank = userCardList.value.find(
    (item: any) => item.id == formData.userCardId
  );
};
const selectBank = (item: any, index: number) => {
  console.log(item, index);
  formData.userCardId = item.id;
};
const drawerConfirm = async (index: number) => {
  // activeIndex.value = index;
  formData.exchangeType = bussinessPriceType[index].value;
  formData.exchangeTypeStr = bussinessPriceType[index].label;
  showDrawer.value = false;
  totalAmount.value = userInfo.value[exchangeTypeEnum[formData.exchangeType]];
};
const checkConfirm = async (pwd: string) => {
  checkPay.value = false;
  uni.showLoading({
    title: "提现中...",
    mask: true,
  });
  await addCashOrder({
    amount: formData.giveAccountAmount,
    userCardId: formData.userCardId,
    cashType: formData.exchangeType,
  });
  uni.hideLoading();
  showTost("提现成功", () => {
    uni.navigateBack();
  });
  store.setUserInfo();
};
const confrim = async () => {
  if (!formData.giveAccountAmount) {
    showTost("请输入提现金额");
    return;
  }
  if (!formData.userCardId) {
    showTost("请选择添加方式");
    return;
  }
  if (userInfo.value.withdrawStatus === "1") {
    showTost("当前用户暂无提现权限！");
    return;
  }
  if (
    formData.giveAccountAmount % 10 !== 0 ||
    formData.giveAccountAmount < 100
  ) {
    showTost("提现金额必须是10的倍数并且大于100");
    return;
  }

  if (!Number.isInteger(Number(formData.giveAccountAmount))) {
    showTost("提现金额必须为整数");
    return;
  }
  if (Number(formData.giveAccountAmount) > Number(totalAmount.value)) {
    showTost("提现金额不能大于可提现金额");
    return;
  }

  checkPay.value = true;
};

const addBank = async (data: any) => {
  await addUserCard({ ...data, cardType: "1" });
  showTost("添加成功", () => {
    showAddBank.value = false;
    getUserCardList(); // getUserCardList 会自动处理选择逻辑
  });
};

const toDetail = () => {
  uni.navigateTo({
    url: "/pages/withdrawal/result",
  });
};

// 移除编辑和删除功能

onLoad((options) => {
  if (options?.selectType) {
    formData.exchangeType = options.selectType;
    const index = bussinessPriceType.findIndex(
      (item) => item.value == options.selectType
    );
    formData.exchangeTypeStr = bussinessPriceType[index].label;
    activeIndex.value = index;
    totalAmount.value = userInfo.value[exchangeTypeEnum[options.selectType]];
  } else {
    formData.exchangeType = bussinessPriceType[0].value;
    formData.exchangeTypeStr = bussinessPriceType[0].label;
    totalAmount.value = userInfo.value[exchangeTypeEnum[formData.exchangeType]];
  }
  getUserCardList();
});
</script>

<style lang="scss" scoped>
.make_present {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: url("../../static/images/zz_bg.png") no-repeat center;
  background-position: 100% 360rpx;
  background-position: top;
  background-color: #f5f5f5;
  .exchangeType {
    padding: 12rpx 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 32rpx;
  }

  .make_title {
    width: calc(100% - 48rpx);
    margin: 60rpx auto;
    @include flexC;
    position: relative;
    text {
      margin-left: 16rpx;
      font-weight: 400;
      color: #fff;
    }

    .price {
      @include dprice(52rpx);
      color: #fff;
      font-size: 32px !important;
      margin-top: 16rpx;
    }
    .but {
      position: absolute;
      right: 0;
      top: 0;
    }
  }

  .explain_text {
    @include dfont(26rpx);
    color: #a0a0ad;
    margin-top: 20rpx;
  }

  .bottoms {
    margin-top: 40rpx;
    padding: 0 12rpx;
  }
}

input {
  font-size: 32rpx;
  padding: 12rpx 0;
}
.bank_list {
  @include flexRS;
  width: 100%;
  padding: 24rpx;
  border-bottom: 1rpx solid #f5f5f5;
  margin: 0 auto;
  box-sizing: border-box;
  font-size: 24rpx !important;
  .bank_item_left {
    @include flexR;
    .bank_item_select {
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
      background-color: #fff;
      margin-right: 12rpx;
      @include flexCC;
    }
  }
  .bank_name {
    color: #222;
    margin-right: 12rpx;
    width: 160rpx;
    @include overflow;
  }
  .bank_cardNum {
    color: #222;
    margin-left: 12rpx;
    flex: 1;
    @include overflow;
  }
  image {
    width: 32rpx;
    height: 32rpx;
  }
}
.bottoms {
  margin: 32rpx 0;
  padding: 0 24rpx;
  box-sizing: border-box;
  width: 100%;
}
</style>
